package com.sddnytsh.body_buildingsystem.components

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.graphics.Color
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.DietApiService
import com.sddnytsh.body_buildingsystem.topic.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

// 辅助函数
fun getCurrentDate(): String {
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    return sdf.format(Date())
}

fun getYesterdayDate(): String {
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.DAY_OF_MONTH, -1)
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    return sdf.format(calendar.time)
}

fun getDayBeforeYesterdayDate(): String {
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.DAY_OF_MONTH, -2)
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    return sdf.format(calendar.time)
}

// 营养汇总卡片组件
@Composable
fun NutritionSummaryCard(summary: NutritionSummary) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "📊 营养汇总",
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF4361EE)
                )
                Text(
                    text = "今日",
                    style = MaterialTheme.typography.bodyMedium,
                    color = Color(0xFF757575),
                    modifier = Modifier
                        .background(
                            Color(0xFFF3E5F5),
                            androidx.compose.foundation.shape.RoundedCornerShape(8.dp)
                        )
                        .padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }
            Spacer(modifier = Modifier.height(16.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                NutritionItem("🔥", "热量", "${summary.totalCalories.toInt()}", "大卡", Color(0xFFE91E63))
                NutritionItem("🥩", "蛋白质", "${summary.totalProtein.toInt()}", "g", Color(0xFF4361EE))
                NutritionItem("🍞", "碳水", "${summary.totalCarbohydrates.toInt()}", "g", Color(0xFF3F51B5))
                NutritionItem("🧈", "脂肪", "${summary.totalFat.toInt()}", "g", Color(0xFF9C27B0))
            }
        }
    }
}

@Composable
fun NutritionItem(emoji: String, label: String, value: String, unit: String, color: Color) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.padding(horizontal = 4.dp)
    ) {
        Text(
            text = emoji,
            style = MaterialTheme.typography.titleLarge
        )
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = value,
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            color = color
        )
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = Color(0xFF757575)
        )
        Text(
            text = unit,
            style = MaterialTheme.typography.bodySmall,
            color = Color(0xFF757575)
        )
    }
}

// 饮食记录项组件
@Composable
fun DietRecordItem(record: DietRecord, onRemove: () -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 6.dp),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = androidx.compose.foundation.shape.RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                modifier = Modifier.weight(1f),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 食物图标
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .background(
                            Color(0xFFF3E5F5),
                            androidx.compose.foundation.shape.CircleShape
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "🍎",
                        style = MaterialTheme.typography.titleMedium
                    )
                }
                
                Spacer(modifier = Modifier.width(12.dp))
                
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = record.foodName,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF212121)
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "${record.amount}g",
                            style = MaterialTheme.typography.bodyMedium,
                            color = Color(0xFF757575)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "•",
                            color = Color(0xFFBDBDBD)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "${record.totalCalories.toInt()} 大卡",
                            style = MaterialTheme.typography.bodyMedium,
                            color = Color(0xFFE91E63),
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
            }
            
            IconButton(
                onClick = onRemove,
                modifier = Modifier.size(32.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Delete,
                    contentDescription = "删除",
                    tint = Color(0xFFE57373),
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}

// 添加食物对话框组件
@Composable
fun AddFoodDialog(
    foodList: List<FoodInfo>,
    foodCategories: List<String>,
    selectedCategory: String,
    searchKeyword: String,
    selectedFood: FoodInfo?,
    amount: String,
    selectedMealType: String,
    isLoadingFoods: Boolean,
    isCreatingRecord: Boolean,
    onCategoryChange: (String) -> Unit,
    onSearchChange: (String) -> Unit,
    onFoodSelect: (FoodInfo) -> Unit,
    onAmountChange: (String) -> Unit,
    onMealTypeChange: (String) -> Unit,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("添加食物")
        },
        text = {
            Column {
                // 分类选择
                var categoryExpanded by remember { mutableStateOf(false) }
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text("分类:")
                    Box {
                        TextButton(onClick = { categoryExpanded = true }) {
                            Text(selectedCategory)
                            Icon(
                                imageVector = Icons.Default.KeyboardArrowDown,
                                contentDescription = null,
                                modifier = Modifier.size(16.dp)
                            )
                        }
                        DropdownMenu(
                            expanded = categoryExpanded,
                            onDismissRequest = { categoryExpanded = false }
                        ) {
                            foodCategories.forEach { category ->
                                DropdownMenuItem(
                                    text = { Text(category) },
                                    onClick = {
                                        onCategoryChange(category)
                                        categoryExpanded = false
                                    }
                                )
                            }
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 搜索框
                OutlinedTextField(
                    value = searchKeyword,
                    onValueChange = onSearchChange,
                    label = { Text("搜索食物") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 食物列表
                if (isLoadingFoods) {
                    CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally))
                } else {
                    LazyColumn(
                        modifier = Modifier.height(200.dp)
                    ) {
                        items(foodList) { food ->
                            FoodItem(
                                food = food,
                                isSelected = selectedFood?.id == food.id,
                                onClick = { onFoodSelect(food) }
                            )
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 已选食物信息
                selectedFood?.let { food ->
                    Text(
                        text = "已选: ${food.name}",
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // 食用量输入
                    OutlinedTextField(
                        value = amount,
                        onValueChange = onAmountChange,
                        label = { Text("食用量(g)") },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                        modifier = Modifier.fillMaxWidth()
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // 餐次选择
                    var mealExpanded by remember { mutableStateOf(false) }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("餐次:")
                        Box {
                            TextButton(onClick = { mealExpanded = true }) {
                                Text(selectedMealType)
                                Icon(
                                    imageVector = Icons.Default.KeyboardArrowDown,
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp)
                                )
                            }
                            DropdownMenu(
                                expanded = mealExpanded,
                                onDismissRequest = { mealExpanded = false }
                            ) {
                                listOf("早餐", "午餐", "晚餐", "加餐").forEach { mealType ->
                                    DropdownMenuItem(
                                        text = { Text(mealType) },
                                        onClick = {
                                            onMealTypeChange(mealType)
                                            mealExpanded = false
                                        }
                                    )
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Button(
                onClick = onConfirm,
                enabled = selectedFood != null && amount.isNotBlank() && !isCreatingRecord
            ) {
                if (isCreatingRecord) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        color = Color.White
                    )
                } else {
                    Text("确认添加")
                }
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

// 食物选择项组件
@Composable
fun FoodItem(
    food: FoodInfo,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
            .background(if (isSelected) Color.Blue.copy(alpha = 0.1f) else Color.Transparent),
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) Color.Blue.copy(alpha = 0.1f) else Color.Transparent
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = food.name,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium
                )
                Text(
                    text = "${food.calories} 大卡/100g",
                    style = MaterialTheme.typography.bodySmall,
                    color = Color.Gray
                )
            }
            
            if (isSelected) {
                Icon(
                    imageVector = Icons.Default.Check,
                    contentDescription = "已选择",
                    tint = Color.Blue
                )
            }
        }
    }
}

// 日历式日期选择器对话框
@Composable
fun DatePickerDialogComponent(
    showDialog: Boolean,
    currentDate: String,
    onDateSelected: (String) -> Unit,
    onDismiss: () -> Unit
) {
    if (showDialog) {
        val calendar = Calendar.getInstance()
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        
        try {
            calendar.time = sdf.parse(currentDate) ?: Date()
        } catch (e: Exception) {
            calendar.time = Date()
        }
        
        var currentMonth by remember { mutableStateOf(calendar.get(Calendar.MONTH)) }
        var currentYear by remember { mutableStateOf(calendar.get(Calendar.YEAR)) }
        var selectedDay by remember { mutableStateOf(calendar.get(Calendar.DAY_OF_MONTH)) }
        
        AlertDialog(
            onDismissRequest = onDismiss,
            title = {
                Text(
                    text = "选择日期",
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold
                )
            },
            text = {
                Column {
                    // 月份导航
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        IconButton(
                            onClick = {
                                if (currentMonth == 0) {
                                    currentMonth = 11
                                    currentYear--
                                } else {
                                    currentMonth--
                                }
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.KeyboardArrowUp,
                                contentDescription = "上个月",
                                tint = Color(0xFF4361EE)
                            )
                        }
                        
                        Text(
                            text = "${currentYear}年${String.format("%02d", currentMonth + 1)}月",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF212121)
                        )
                        
                        IconButton(
                            onClick = {
                                if (currentMonth == 11) {
                                    currentMonth = 0
                                    currentYear++
                                } else {
                                    currentMonth++
                                }
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.KeyboardArrowDown,
                                contentDescription = "下个月",
                                tint = Color(0xFF4361EE)
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    // 星期标题
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceEvenly
                    ) {
                        listOf("一", "二", "三", "四", "五", "六", "日").forEach { day ->
                            Text(
                                text = day,
                                style = MaterialTheme.typography.bodyMedium,
                                fontWeight = FontWeight.Medium,
                                color = Color(0xFF757575),
                                modifier = Modifier.weight(1f),
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // 日历网格
                    CalendarGrid(
                        year = currentYear,
                        month = currentMonth,
                        selectedDay = selectedDay,
                        onDaySelected = { day ->
                            selectedDay = day
                        }
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    // 今天按钮
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Start
                    ) {
                        TextButton(
                            onClick = {
                                val today = Calendar.getInstance()
                                currentYear = today.get(Calendar.YEAR)
                                currentMonth = today.get(Calendar.MONTH)
                                selectedDay = today.get(Calendar.DAY_OF_MONTH)
                            }
                        ) {
                            Text("今天", color = Color(0xFF4361EE))
                        }
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        val selectedCalendar = Calendar.getInstance()
                        selectedCalendar.set(currentYear, currentMonth, selectedDay)
                        val selectedDateString = sdf.format(selectedCalendar.time)
                        onDateSelected(selectedDateString)
                        onDismiss()
                    },
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4361EE))
                ) {
                    Text("确定", color = Color.White)
                }
            },
            dismissButton = {
                TextButton(onClick = onDismiss) {
                    Text("取消", color = Color(0xFF757575))
                }
            }
        )
    }
}

// 日历网格组件
@Composable
fun CalendarGrid(
    year: Int,
    month: Int,
    selectedDay: Int,
    onDaySelected: (Int) -> Unit
) {
    val calendar = Calendar.getInstance()
    calendar.set(year, month, 1)
    
    val firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
    val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
    
    // 计算第一天是星期几（1=周一，7=周日）
    val startDay = if (firstDayOfWeek == 1) 1 else firstDayOfWeek - 1
    
    // 创建6行7列的网格
    val weeks = mutableListOf<List<Int>>()
    var currentWeek = mutableListOf<Int>()
    
    // 填充第一周的空格
    repeat(startDay - 1) {
        currentWeek.add(0) // 0表示空
    }
    
    // 填充当月的日期
    for (day in 1..daysInMonth) {
        currentWeek.add(day)
        if (currentWeek.size == 7) {
            weeks.add(currentWeek)
            currentWeek = mutableListOf()
        }
    }
    
    // 填充最后一周的空格
    while (currentWeek.size < 7 && currentWeek.isNotEmpty()) {
        currentWeek.add(0)
    }
    if (currentWeek.isNotEmpty()) {
        weeks.add(currentWeek)
    }
    
    Column {
        weeks.forEach { week ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                week.forEach { day ->
                    Box(
                        modifier = Modifier
                            .size(40.dp)
                            .background(
                                if (day == selectedDay) Color(0xFF4361EE) else Color.Transparent,
                                androidx.compose.foundation.shape.CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        if (day > 0) {
                            Text(
                                text = day.toString(),
                                style = MaterialTheme.typography.bodyMedium,
                                color = if (day == selectedDay) Color.White else Color(0xFF212121),
                                fontWeight = if (day == selectedDay) FontWeight.Bold else FontWeight.Normal,
                                modifier = Modifier.clickable { onDaySelected(day) }
                            )
                        }
                    }
                }
            }
            Spacer(modifier = Modifier.height(4.dp))
        }
    }
}

// 创建饮食记录
fun createDietRecord(
    dietApiService: DietApiService,
    request: DietRecordCreateRequest,
    onResult: (Boolean) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        dietApiService.createDietRecord(request).fold(
            onSuccess = { 
                onResult(true)
            },
            onFailure = { 
                onResult(false)
            }
        )
    }
}

@Composable
fun Page2() {
    val dietApiService = remember { DietApiService() }
    
    // 状态管理
    var selectedDate by remember { mutableStateOf<String>(getCurrentDate()) }
    var selectedFood by remember { mutableStateOf<FoodInfo?>(null) }
    var amount by remember { mutableStateOf("") }
    var selectedMealType by remember { mutableStateOf("早餐") }
    var expanded by remember { mutableStateOf(false) }
    var showAddFoodDialog by remember { mutableStateOf(false) }
    var showHistoryDialog by remember { mutableStateOf(false) }
    var showDatePicker by remember { mutableStateOf(false) }
    
    // 数据状态
    var foodList by remember { mutableStateOf<List<FoodInfo>>(emptyList()) }
    var foodCategories by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedCategory by remember { mutableStateOf("全部分类") }
    var searchKeyword by remember { mutableStateOf("") }
    var dietRecords by remember { mutableStateOf<List<DietRecord>>(emptyList()) }
    var nutritionSummary by remember { mutableStateOf<NutritionSummary?>(null) }
    
    // 加载状态
    var isLoadingFoods by remember { mutableStateOf(false) }
    var isLoadingRecords by remember { mutableStateOf(false) }
    var isLoadingSummary by remember { mutableStateOf(false) }
    var isCreatingRecord by remember { mutableStateOf(false) }
    
    // 初始化数据
    LaunchedEffect(Unit) {
        isLoadingFoods = true
        
        // 加载食物分类
        CoroutineScope(Dispatchers.IO).launch {
            dietApiService.getFoodCategories().fold(
                onSuccess = { categories ->
                    foodCategories = categories
                },
                onFailure = { 
                    foodCategories = emptyList()
                }
            )
        }
        
        // 加载食物列表
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val result = if (selectedCategory == "全部分类") {
                    dietApiService.getAllFoods()
                } else {
                    dietApiService.getFoodsByCategory(selectedCategory)
                }
                
                result.fold(
                    onSuccess = { foods ->
                        foodList = foods
                        isLoadingFoods = false
                    },
                    onFailure = { 
                        foodList = emptyList()
                        isLoadingFoods = false
                    }
                )
            } catch (e: Exception) {
                Log.e("Page2", "加载食物异常: ${e.message}")
                foodList = emptyList()
                isLoadingFoods = false
            }
        }
        
        val currentUserId = UserState.currentUserId
        if (currentUserId != null) {
            // 加载饮食数据
            CoroutineScope(Dispatchers.IO).launch {
                val recordsResult = dietApiService.getDietRecordsByDate(currentUserId, selectedDate)
                val summaryResult = dietApiService.getNutritionSummary(currentUserId, selectedDate)
                
                val records = recordsResult.getOrElse { emptyList() }
                val summary = summaryResult.getOrNull()
                
                dietRecords = records
                nutritionSummary = summary
            }
        }
    }
    
    // 当日期改变时重新加载数据
    LaunchedEffect(selectedDate) {
        val currentUserId = UserState.currentUserId
        if (currentUserId != null) {
            // 加载饮食数据
            CoroutineScope(Dispatchers.IO).launch {
                val recordsResult = dietApiService.getDietRecordsByDate(currentUserId, selectedDate)
                val summaryResult = dietApiService.getNutritionSummary(currentUserId, selectedDate)
                
                val records = recordsResult.getOrElse { emptyList() }
                val summary = summaryResult.getOrNull()
                
                dietRecords = records
                nutritionSummary = summary
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF5F5F5))
    ) {
        // 顶部栏
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(64.dp)
                .background(
                    brush = androidx.compose.ui.graphics.Brush.verticalGradient(
                        colors = listOf(Color(0xFF4361EE), Color(0xFF3A0CA3))
                    )
                )
        ) {
            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 16.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "🍽️ 饮食记录",
                    color = Color.White,
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold
                )

                IconButton(
                    onClick = { showHistoryDialog = true }
                ) {
                    Icon(
                        imageVector = Icons.Default.List,
                        contentDescription = "历史记录",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
        
        // 日期选择器
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
            shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Filled.DateRange,
                        contentDescription = "日期",
                        tint = Color(0xFF4361EE),
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "选择日期:",
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF212121)
                    )
                }
                
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    OutlinedTextField(
                        value = selectedDate,
                        onValueChange = { },
                        modifier = Modifier.width(140.dp),
                        singleLine = true,
                        readOnly = true,
                        colors = androidx.compose.material3.OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color(0xFF4361EE),
                            unfocusedBorderColor = Color(0xFFE0E0E0)
                        ),
                        trailingIcon = {
                            IconButton(onClick = { showDatePicker = true }) {
                                Icon(
                                    imageVector = Icons.Filled.DateRange,
                                    contentDescription = "选择日期",
                                    tint = Color(0xFF4361EE),
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }
                    )
                }
            }
        }

        // 营养汇总卡片
        nutritionSummary?.let { summary: NutritionSummary ->
            NutritionSummaryCard(summary = summary)
        }
        
        // 主要内容区域
        Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
        ) {
            if (dietRecords.isNotEmpty()) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Default.List,
                        contentDescription = "记录",
                        tint = Color(0xFF4361EE),
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "${selectedDate} 饮食记录",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF212121)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "(${dietRecords.size}项)",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color(0xFF757575)
                    )
                }

                LazyColumn(
                    modifier = Modifier.weight(1f)
                ) {
                    items(dietRecords) { record ->
                        DietRecordItem(
                            record = record,
                            onRemove = {
                                // 删除记录
                                CoroutineScope(Dispatchers.IO).launch {
                                    dietApiService.deleteDietRecord(record.id).fold(
                                        onSuccess = {
                                            // 重新加载数据
                                            val currentUserId = UserState.currentUserId
                                            if (currentUserId != null) {
                                                CoroutineScope(Dispatchers.IO).launch {
                                                    val recordsResult = dietApiService.getDietRecordsByDate(currentUserId, selectedDate)
                                                    val summaryResult = dietApiService.getNutritionSummary(currentUserId, selectedDate)
                                                    
                                                    val records = recordsResult.getOrElse { emptyList() }
                                                    val summary = summaryResult.getOrNull()
                                                    
                                                    dietRecords = records
                                                    nutritionSummary = summary
                                                }
                                            }
                                        },
                                        onFailure = { /* 处理错误 */ }
                                    )
                                }
                            }
                        )
                    }
                }
            } else {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(32.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .background(
                                Color(0xFFF3E5F5),
                                androidx.compose.foundation.shape.CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Outlined.ShoppingCart,
                            contentDescription = "暂无记录",
                            modifier = Modifier.size(40.dp),
                            tint = Color(0xFF4361EE)
                        )
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "暂无饮食记录",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF757575)
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "点击底部按钮添加食物",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color(0xFFBDBDBD),
                        textAlign = TextAlign.Center
                    )
                }
            }
        }

        // 底部栏
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            shape = androidx.compose.foundation.shape.RoundedCornerShape(16.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = "今日总计",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color(0xFF757575)
                    )
                    Text(
                        text = "${nutritionSummary?.totalCalories?.toInt() ?: 0} 大卡",
                        style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
                        color = Color(0xFFE91E63)
                    )
                }

                Button(
                    onClick = { showAddFoodDialog = true },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF4361EE)
                    ),
                    shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
                    modifier = Modifier.height(48.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Check,
                        contentDescription = "添加",
                        tint = Color.White,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "添加食物",
                        color = Color.White,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        }
    }

    // 添加食物的对话框
    if (showAddFoodDialog) {
        AddFoodDialog(
            foodList = foodList,
            foodCategories = foodCategories,
            selectedCategory = selectedCategory,
            searchKeyword = searchKeyword,
            selectedFood = selectedFood,
            amount = amount,
            selectedMealType = selectedMealType,
            isLoadingFoods = isLoadingFoods,
            isCreatingRecord = isCreatingRecord,
            onCategoryChange = { category ->
                selectedCategory = category
                isLoadingFoods = true
                Log.d("Page2", "选择分类: $category")
                
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        val result = if (category == "全部分类") {
                            dietApiService.getAllFoods()
                        } else {
                            dietApiService.getFoodsByCategory(category)
                        }
                        
                        result.fold(
                            onSuccess = { foods ->
                                Log.d("Page2", "加载到食物数量: ${foods.size}")
                                foodList = foods
                                isLoadingFoods = false
                            },
                            onFailure = { 
                                Log.d("Page2", "加载食物失败")
                                foodList = emptyList()
                                isLoadingFoods = false
                            }
                        )
                    } catch (e: Exception) {
                        Log.e("Page2", "加载食物异常: ${e.message}")
                        foodList = emptyList()
                        isLoadingFoods = false
                    }
                }
            },
            onSearchChange = { keyword ->
                searchKeyword = keyword
                isLoadingFoods = true
                Log.d("Page2", "搜索关键词: $keyword")
                
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        val result = if (keyword.isBlank()) {
                            if (selectedCategory == "全部分类") {
                                dietApiService.getAllFoods()
                            } else {
                                dietApiService.getFoodsByCategory(selectedCategory)
                            }
                        } else {
                            dietApiService.searchFoods(keyword)
                        }
                        
                        result.fold(
                            onSuccess = { foods ->
                                Log.d("Page2", "搜索到食物数量: ${foods.size}")
                                foodList = foods
                                isLoadingFoods = false
                            },
                            onFailure = { 
                                Log.d("Page2", "搜索食物失败")
                                foodList = emptyList()
                                isLoadingFoods = false
                            }
                        )
                    } catch (e: Exception) {
                        Log.e("Page2", "搜索食物异常: ${e.message}")
                        foodList = emptyList()
                        isLoadingFoods = false
                    }
                }
            },
            onFoodSelect = { food ->
                selectedFood = food
            },
            onAmountChange = { amount = it },
            onMealTypeChange = { selectedMealType = it },
            onConfirm = {
                selectedFood?.let { food ->
                    val amountValue = amount.toDoubleOrNull() ?: 0.0
                    if (amountValue > 0) {
                        isCreatingRecord = true
                        val currentUserId = UserState.currentUserId
                        if (currentUserId != null) {
                            createDietRecord(
                                dietApiService,
                                DietRecordCreateRequest(
                                    userId = currentUserId,
                                    foodId = food.id,
                                    amount = amountValue,
                                    mealTime = "${selectedDate}T12:00:00",
                                    mealType = selectedMealType
                                )
                            ) { success ->
                                isCreatingRecord = false
                                if (success) {
                                    // 重新加载数据
                                    val currentUserId = UserState.currentUserId
                                    if (currentUserId != null) {
                                        CoroutineScope(Dispatchers.IO).launch {
                                            val recordsResult = dietApiService.getDietRecordsByDate(currentUserId, selectedDate)
                                            val summaryResult = dietApiService.getNutritionSummary(currentUserId, selectedDate)
                                            
                                            val records = recordsResult.getOrElse { emptyList() }
                                            val summary = summaryResult.getOrNull()
                                            
                                            dietRecords = records
                                            nutritionSummary = summary
                                        }
                                    }
                                    // 重置表单
                                    selectedFood = null
                                    amount = ""
                                    showAddFoodDialog = false
                                }
                            }
                    }
                }
            }
            },
            onDismiss = { showAddFoodDialog = false }
        )
    }

    // 历史记录对话框
    if (showHistoryDialog) {
        AlertDialog(
            onDismissRequest = { showHistoryDialog = false },
            title = {
                Text("历史记录")
            },
            text = {
                Text("历史记录功能待实现")
            },
            confirmButton = {
                Button(
                    onClick = { showHistoryDialog = false }
                ) {
                    Text("关闭")
                }
            }
        )
    }
    
    // 日期选择器对话框
    DatePickerDialogComponent(
        showDialog = showDatePicker,
        currentDate = selectedDate,
        onDateSelected = { newDate ->
            selectedDate = newDate
        },
        onDismiss = { showDatePicker = false }
    )
}

// 加载食物分类
fun loadFoodCategories(
    dietApiService: DietApiService,
    onResult: (List<String>) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        dietApiService.getFoodCategories().fold(
            onSuccess = { categories ->
                onResult(categories)
            },
            onFailure = { 
                onResult(emptyList())
            }
        )
    }
}

// 加载食物列表
fun loadFoods(
    dietApiService: DietApiService,
    category: String,
    keyword: String,
    onResult: (List<FoodInfo>) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        try {
            val result = if (keyword.isNotBlank()) {
                dietApiService.searchFoods(keyword)
            } else if (category != "全部分类") {
                dietApiService.getFoodsByCategory(category)
            } else {
                dietApiService.getAllFoods()
            }
            
            result.fold(
                onSuccess = { foods ->
                    onResult(foods)
                },
                onFailure = { error ->
                    Log.e("Page2", "加载食物失败: ${error.message}")
                    onResult(emptyList())
                }
            )
        } catch (e: Exception) {
            Log.e("Page2", "加载食物异常: ${e.message}")
            onResult(emptyList())
        }
    }
}

// 加载饮食数据
fun loadDietData(
    dietApiService: DietApiService,
    userId: Long,
    date: String,
    onResult: (List<DietRecord>, NutritionSummary?) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        val recordsResult = dietApiService.getDietRecordsByDate(userId, date)
        val summaryResult = dietApiService.getNutritionSummary(userId, date)
        
        val records = recordsResult.getOrElse { emptyList() }
        val summary = summaryResult.getOrNull()
        
        onResult(records, summary)
    }
}